//
//  HomeViewController.m
//  CityFire
//
//  Created by Liuyz on 2017/7/31.
//  Copyright © 2017年 刘养柱. All rights reserved.
//

#import "HomeViewController.h"
#import "CompanySelectViewController.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "DeviceViewModel.h"
#import "CsutomMapAnnotationView.h"
#import "MonitorViewModel.h"
#import<AudioToolbox/AudioToolbox.h>


static SystemSoundID shake_sound_male_id = 0;

@interface HomeViewController ()<MAMapViewDelegate, AMapLocationManagerDelegate, AMapSearchDelegate>

@property (nonatomic, weak) IBOutlet UIButton *selectBtn;
@property (nonatomic, strong) MonitorViewModel *monitorViewModel;
@property (nonatomic, weak) IBOutlet MAMapView *mapView;

@property (nonatomic,assign) BOOL shouldKeepRunning;
@property (nonatomic, strong) AMapLocationManager *locationManager;
//@property (nonatomic, strong) CsutomMapAnnotationView *pointAnnotaiton;
@property (nonatomic, assign)MAPointAnnotation *pointAnnotation ;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
//自已的位置
@property (nonatomic, assign) CLLocationCoordinate2D myCoordinate;
@property(nonatomic,assign) BOOL isStart;
@property (nonatomic,assign) CsutomMapAnnotationView *lastAnotationView;

@property (nonatomic, strong) DeviceViewModel *deviceViewModel;
@property (nonatomic, strong) NSString * orgName;
@property (nonatomic, assign) BOOL isSetAlias ;
//一个search对象，用于地理位置逆编码
@property(nonatomic,strong)AMapSearchAPI *search;

//当前定位
@property(nonatomic,strong)CLLocation *currentLocation;

@end

@implementation HomeViewController
- (IBAction)returnMyLocationClick:(id)sender {
    //显示当前定位功能
    [self.mapView setCenterCoordinate:self.myCoordinate animated:YES];
}

- (MonitorViewModel *)monitorViewModel
{
    if (_monitorViewModel == nil) {
        _monitorViewModel = [[MonitorViewModel alloc] init];
    }
    
    return _monitorViewModel;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.locationManager startUpdatingLocation];
    self.shouldKeepRunning=YES;
    [self.monitorViewModel getQueryRealTimeWarning:nil];
    
    
    
                NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *userId = [userDefaultes stringForKey:@"userId"];
    NSString *userName = [userDefaultes stringForKey:@"userName"];
    
    if (userName!=nil&&![userName isEqualToString:@""]) {
        //设置别名 当前别名
        
        [JPUSHService setAlias:userName completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
           NSLog(@"极光推送别名注册完成 seq %ld and iResCode ,");
        } seq:101];
        
    }
   
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = kHOME_TITLE;
    
    self.isStart = NO;
    self.isSetAlias=YES;
    
    [self initSearch];
    
    [self configUI];
    
    [self configLocationManager];
    
    [self bindRAC];
    
    self.shouldKeepRunning=NO;
    
    [self chechLocation];
   
}

-(void)chechLocation{
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL isAceessLocation = [defaults boolForKey:@"isAceessLocation"];
    
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(childTask) userInfo:nil repeats:YES];
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                   message:@"应用将采集你的位置信息来加载附近的服务 是否允许？"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"同意" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              //响应事件
                                                                 [defaults setBool:YES forKey:@"isAceessLocation"];
                                                              NSLog(@"action = %@", action);
                                                          }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"拒绝" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                             NSLog(@"action = %@", action);
                                                              [defaults setBool:NO forKey:@"isAceessLocation"];
                                                         }];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    
    if(!isAceessLocation){
    [self presentViewController:alert animated:YES completion:nil];
    }
    
    
}

//子线程方法
-(void) childTask{
    NSLog(@"child timer run");
    if (!self.shouldKeepRunning) {
         self.shouldKeepRunning=YES;
         [self.monitorViewModel getQueryRealTimeWarning:nil];
    }
}
- (void)bindRAC {
    [RACObserve(self.deviceViewModel, devicesArray) subscribeNext:^(NSArray *devicesArray) {
        if (devicesArray) {
            DeviceModel *deviceModel = [devicesArray firstObject];
            
            MAPointAnnotation *anntation = [[MAPointAnnotation alloc] init];
            
            anntation.coordinate = CLLocationCoordinate2DMake([deviceModel.latitude floatValue], [deviceModel.longitude floatValue]);
            anntation.title = deviceModel.deviceName;
            
            self.coordinate=anntation.coordinate;
            
                [self addAnomationWithCoor:anntation.coordinate];
            
            
           
        }
    }];
    
    [RACObserve(self.monitorViewModel, monitorArray) subscribeNext:^(NSArray *mArray) {
        [self endRefresh];
         self.shouldKeepRunning=NO;
        if (mArray.count) {
           
            
                
                NSInteger isPlay =0;
                for (MonitorModel *model in mArray) {
                    NSString *status = model.record2;
                    //报警
                    if ([status isEqualToString:@"报警"]) {
                        isPlay =3;
                    }
                }
                
                if (isPlay==3) {
                    //播放报警
                    [self playSound:3];
                }else{
                    for (MonitorModel *model in mArray) {
                        NSString *status = model.record2;
                        //报警
                        if ([status isEqualToString:@"故障"]) {
                            isPlay =2;
                        }
                    }
                    if (isPlay==2) {
                        //故障
                        [self playSound:2];
                    }
                }
            }
         }];
        
}

     -(void) playSound :(NSInteger ) index{
         NSString *path = [[NSBundle mainBundle] pathForResource:@"6" ofType:@"mp3"];
         if (index==3) {
             //报警
             path = [[NSBundle mainBundle] pathForResource:@"6" ofType:@"mp3"];
         } else {
             //故障
             path = [[NSBundle mainBundle] pathForResource:@"7" ofType:@"mp3"];
         }
         
         
         if (path) {
             //注册声音到系统
             
             AudioServicesCreateSystemSoundID(((__bridge CFURLRef)[NSURL fileURLWithPath:path]),&shake_sound_male_id);
             
             BOOL isPlay = [[NSUserDefaults readUserDataWithKey:kNSUSERDEFAULT_KEY_ISSOUND] boolValue];
             BOOL isVip =[[NSUserDefaults readUserDataWithKey:kNSUSERDEFAULT_KEY_VIBRATE] boolValue];
             if (isPlay) {
                 AudioServicesPlaySystemSound(shake_sound_male_id);
             }
             if (isVip) {
                 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
             }
             
             //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
         }
         
         
         
         //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
         
     }
- (IBAction)companySelectClicked:(id)sender
{
    CompanySelectViewController *companyVC = kVCFromSB(kHomeStoryBoard, CompanySelectViewController);
    [companyVC setSelectedOrgnameBlock:^(NSString *orgName) {
        self.orgName = orgName;
        [self.deviceViewModel getQueryPersonOrgDevices:@{@"orgname" : orgName}];
    }];
    companyVC.hidesBottomBarWhenPushed = YES;
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL isAceessLocation = [defaults boolForKey:@"isAceessLocation"];
    if (isAceessLocation) {
         [self.navigationController pushViewController:companyVC animated:YES];
    } else {
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"应用将采集你的位置信息来加载附近的服务 是否允许？"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"同意" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  //响应事件
                                                                   [self.navigationController pushViewController:companyVC animated:YES];
                                                              }];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"拒绝" style:UIAlertActionStyleDefault
                                                             handler:^(UIAlertAction * action) {
                                                                 //响应事件
                                                               
                                                             }];
        
        [alert addAction:defaultAction];
        [alert addAction:cancelAction];
        
       
            [self presentViewController:alert animated:YES completion:nil];
        
    }
    
   
}

#pragma mark - Action Handle

- (void)configLocationManager
{
    [self.mapView setDelegate:self];
    
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    [self.locationManager setAllowsBackgroundLocationUpdates:NO];
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    self.mapView.showsScale = YES;
    
}

#pragma mark --标记添加大头针
-(void)addAnomationWithCoor:(CLLocationCoordinate2D)coor{
    //地理坐标反编码为文字
    AMapReGeocodeSearchRequest *request =[[AMapReGeocodeSearchRequest alloc] init];
    request.location =[AMapGeoPoint locationWithLatitude:coor.latitude longitude:coor.longitude];
    [_search AMapReGoecodeSearch:request];
    //_anomationPoint = [[MAPointAnnotation alloc] init];
    //_anomationPoint.coordinate = coor;
    //[self.mapView removeAnnotation:_anomationPoint];
    //[self.mapView addAnnotation:_anomationPoint];
    //将标记点的位置放在地图的中心
    //self.mapView.centerCoordinate = coor;
    self.coordinate=coor;
    
    
}

-(void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{
    self.mapView.centerCoordinate = self.coordinate;
}


#pragma mark --设置大头针上方气泡的内容的代理方法
-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    
    NSLog(@"设置大头针上方气泡的内容的代理方法");
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = NO;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        
        annotationView.pinColor = MAPinAnnotationColorPurple;
    
        return annotationView;
    }
    
//    //大头针标注
//    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {//判断是否是自己的定位气泡，如果是自己的定位气泡，不做任何设置，显示为蓝点，如果不是自己的定位气泡，比如大头针就会进入
//        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
//        CsutomMapAnnotationView *annotationView = (CsutomMapAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
//        if (annotationView == nil) {
//            annotationView = [[CsutomMapAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
//        }
//        annotationView.frame = CGRectMake(0, 0, 100, 100);
//        annotationView.canShowCallout= NO;       //设置气泡可以弹出，默认为NO
//        //annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
//        annotationView.draggable = YES;           //设置标注可以拖动，默认为NO
//        //        annotationView.pinColor = MAPinAnnotationColorPurple;
//        //设置大头针显示的图片
//        //        if (!self.locationPointImgName) {
//        annotationView.image = [UIImage imageNamed:@"icon_location.png"];
//        //        }else{
//        //            annotationView.image = [UIImage imageNamed:self.locationPointImgName];
//        //        }
//        //点击大头针显示的左边的视图
//        //        UIImageView *imageV = [[UIImageView alloc]init];
//        //        if (!self.destinationImgName) {
//        //            imageV.image = [UIImage imageNamed:@"目的地"];
//        //        }else{
//        //            imageV.image = [UIImage imageNamed:self.destinationImgName];
//        //        }
//        //        annotationView.leftCalloutAccessoryView = imageV;
//        //        点击大头针显示的右边视图
//        //        UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
//        //        rightButton.backgroundColor = [UIColor grayColor];
//        //        [rightButton setTitle:@"导航" forState:UIControlStateNormal];
//        //        [rightButton addTarget:self action:@selector(navBtnClick) forControlEvents:UIControlEventTouchUpInside];
//        //        annotationView.rightCalloutAccessoryView = rightButton;
//        self.lastAnotationView = annotationView;
//        return annotationView;
//    }
    return nil;
}


- (void)showsSegmentAction:(UISegmentedControl *)sender
{
    if (sender.selectedSegmentIndex)
    {
        [self.locationManager stopUpdatingLocation];
        
        //Remove annotation & annotationView
        [self.mapView removeAnnotations:self.mapView.annotations];

    }
    else
    {
        [self.locationManager requestLocationWithReGeocode:NO completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            //            MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
            //            [annotation setCoordinate:location.coordinate];
            //
            //            //有无逆地理信息，annotationView的标题显示的字段不一样
            //            if (regeocode)
            //            {
            //                [annotation setTitle:[NSString stringWithFormat:@"%@", regeocode.formattedAddress]];
            //                [annotation setSubtitle:[NSString stringWithFormat:@"%@-%@-%.2fm", regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]];
            //            }
            //            else
            //            {
            //                [annotation setTitle:[NSString stringWithFormat:@"lat:%f;lon:%f;", location.coordinate.latitude, location.coordinate.longitude]];
            //                [annotation setSubtitle:[NSString stringWithFormat:@"accuracy:%.2fm", location.horizontalAccuracy]];
            //            }
            ////            MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
            ////            pointAnnotation.coordinate = CLLocationCoordinate2DMake(39.989631, 116.481018);
            ////            pointAnnotation.title = @"方恒国际";
            ////            pointAnnotation.subtitle = @"阜通东大街6号";
            //
            ////            [_mapView addAnnotation:pointAnnotation];
            //            [self.mapView addAnnotation:annotation];
            
        }];
    }
}

#pragma mark 搜索请求发起后的回调,用于标记自己当前的位置
/**失败回调*/
-(void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    
    NSLog(@"request: %@------error:  %@",request,error);
}
//*成功回调
-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
    //我们把编码后的地理位置，显示到 大头针的标题和子标题上
    NSString *title =[NSString stringWithFormat:@"%@    (%@)",self.orgName,response.regeocode.addressComponent.city];
    
    
    NSLog(@"%@",title);
    if (title.length == 0) {
        title = response.regeocode.addressComponent.province;
    }
    //    NSLog(@"=====%@",request.location);
    if (request.location.latitude == _currentLocation.coordinate.latitude&&request.location.longitude == _currentLocation.coordinate.longitude) {
        _mapView.userLocation.title = title;
        _mapView.userLocation.subtitle = response.regeocode.formattedAddress;
    }else{
        
        [self.mapView removeAnnotations:self.mapView.annotations];
        
        MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
        pointAnnotation.coordinate = self.coordinate;
        pointAnnotation.title = title;
        pointAnnotation.subtitle = response.regeocode.formattedAddress;
       
        self.pointAnnotation =pointAnnotation;
       // [self.mapView addAnnotation:pointAnnotation];
       self.mapView.centerCoordinate = self.coordinate;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(300.0 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.mapView addAnnotation:pointAnnotation];
            });
        });
        
    }
}

#pragma mark - AMapLocationManager Delegate

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"%s, amapLocationManager = %@, error = %@", __func__, [manager class], error);
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    //    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    
//    if (self.pointAnnotaiton == nil)
//    {
//        self.pointAnnotaiton = [[CsutomMapAnnotationView alloc] init];
//
//        [self.pointAnnotaiton.annotation setCoordinate:location.coordinate];
//
//        [self.mapView addAnnotation:self.pointAnnotaiton.annotation];
//    }
//
//    [self.pointAnnotaiton.annotation setCoordinate:location.coordinate];
    
    //    [self addAnomationWithCoor:location.coordinate];
    
    //    _currentLocation = location;
    
    if (!self.isStart) {
        self.isStart = YES;
        self.myCoordinate =location.coordinate;
        [self.mapView setCenterCoordinate:location.coordinate];
    }else{
        [self.mapView setCenterCoordinate:self.coordinate];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(500.0 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.mapView  selectAnnotation:self.pointAnnotation  animated: YES];
            });
        });
       
    }
    
    [self.mapView setZoomLevel:15.1 animated:NO];
    
    [self.locationManager stopUpdatingLocation];
}

- (void)addAnnotationToMapView:(id<MAAnnotation>)annotation
{
    [self.mapView addAnnotation:annotation];
    
    [self.mapView selectAnnotation:annotation animated:YES];
    [self.mapView setZoomLevel:15.1 animated:NO];
    [self.mapView setCenterCoordinate:annotation.coordinate animated:YES];
}
#pragma mark - MAMapView Delegate
//- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
//{
//    if ([annotation isKindOfClass:[MAPointAnnotation class]])
//    {
//        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
//        
//        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
//        if (annotationView == nil)
//        {
//            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
//        }
//        
//        annotationView.canShowCallout   = NO;
//        annotationView.animatesDrop     = NO;
//        annotationView.draggable        = NO;
//        annotationView.image            = [UIImage imageNamed:@"icon_location.png"];
//        
//        return annotationView;
//    }
//    
//    return nil;
//}

//- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
//{
//    if ([annotation isKindOfClass:[CsutomMapAnnotationView class]])
//    {
//        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
//        CsutomMapAnnotationView *annotationView = (CsutomMapAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
//        if (annotationView == nil)
//        {
//            annotationView = [[CsutomMapAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
//        }
//        annotationView.image = [UIImage imageNamed:@"restaurant"];
//        
//        // 设置为NO，用以调用自定义的calloutView
//        annotationView.canShowCallout = NO;
//        
//        // 设置中心点偏移，使得标注底部中间点成为经纬度对应点
//        annotationView.centerOffset = CGPointMake(0, -18);
//        return annotationView;
//    }
//    return nil;
//}


/**
 UI调整设置
 */
- (void)configUI {
    self.selectBtn.layer.cornerRadius = 8.0f;
    self.selectBtn.layer.masksToBounds = YES;
    
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    //   定位超时时间，最低2s，此处设置为10s
    self.locationManager.locationTimeout =10;
    //   逆地理请求超时时间，最低2s，此处设置为10s
    self.locationManager.reGeocodeTimeout = 10;
}

#pragma mark serach初始化
-(void)initSearch{
    _search =[[AMapSearchAPI alloc] init];
    _search.delegate=self;
}

- (DeviceViewModel *)deviceViewModel
{
    if (_deviceViewModel == nil) {
        _deviceViewModel = [[DeviceViewModel alloc] init];
    }
    
    return _deviceViewModel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views{
    
}

@end
